package com.example.gateway.filter;

import com.example.common.core.AjaxResult;
import com.example.common.entity.ExcpErrResult;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

public class FilterUtil {

    /**
     * 自定义错误
     *
     * @param exchange 请求
     * @param msg      消息
     * @return
     */
    public static Mono<Void> customError(ServerWebExchange exchange, String msg, Integer errorCode) {
//        Map<String, Object> resultMap = new HashMap<>(8);
//        resultMap.put("error_code", errorCode);
//        resultMap.put("msg", StringUtils.isBlank(msg) ? "服务异常！" : msg);
//        AjaxResult ajaxResult = AjaxResult.error(errorCode, msg);
        ExcpErrResult<Object> result = ExcpErrResult.builder().msg("操作失败").code(errorCode).data(msg).build();
        return Mono.defer(() -> {
            ServerHttpResponse response = exchange.getResponse();
            response.getHeaders().add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
            DataBuffer buffer = response.bufferFactory().wrap(result.toString().getBytes(StandardCharsets.UTF_8));
            return response.writeWith(Flux.just(buffer));
        });
    }
}
